package com.cl.short_video_java.common;

import com.cl.short_video_java.service.SysSettingService;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FtpConnectionPool {
    private static SysSettingService settingService;

    public FtpConnectionPool(SysSettingService settingService) {
        this.settingService = settingService;
    }

    @Bean
    public GenericObjectPool<FTPClient> ftpClientPool() {
        GenericObjectPoolConfig<FTPClient> poolConfig = new GenericObjectPoolConfig<>();
        poolConfig.setMaxTotal(10); // 最大连接数
        poolConfig.setMinIdle(2); // 最小空闲连接数
        poolConfig.setMaxIdle(5); // 最大空闲连接数
        poolConfig.setMaxWaitMillis(3000); // 最大等待时间
        poolConfig.setJmxEnabled(false);
        return new GenericObjectPool<>(new FtpClientFactory(), poolConfig);
    }

    private static class FtpClientFactory extends BasePooledObjectFactory<FTPClient> {
        @Override
        public FTPClient create() throws Exception {
            FTPClient ftpClient = new FTPClient();
            String ftpImgServerIp = settingService.getSysSettingByKey("ftp_img_server_ip");
            String ftpPort = settingService.getSysSettingByKey("ftp_port");
            String ftpUser = settingService.getSysSettingByKey("ftp_user");
            String ftpPass = settingService.getSysSettingByKey("ftp_pass");
            ftpClient.connect(ftpImgServerIp, Integer.parseInt(ftpPort));
            ftpClient.login(ftpUser, ftpPass);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            return ftpClient;
        }

        @Override
        public PooledObject<FTPClient> wrap(FTPClient ftpClient) {
            return new DefaultPooledObject<>(ftpClient);
        }

        @Override
        public void destroyObject(PooledObject<FTPClient> p) throws Exception {
            FTPClient ftpClient = p.getObject();
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        }
    }

}
